package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.captchas.v4.proposal_b;

import com.nulldev.util.VariableAPI.ByteUtil;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.security.hashAPI.Hashes;
import com.nulldev.util.security.hashAPI.Hashes.Hashables;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.user.User;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.util.UUIDCookieLoader;
import com.nulldev.util.web.HttpServer3.legacyPages.v1.RequestType;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;

public class TLSCaptchaPage extends HttpPage3 {

	public TLSCaptchaPage() {
		super("/captcha/tls", true);
		super.setCachingMethod(CachingMethod.NO_CACHE);
	}

	@Override
	public Response onRequest(final Request request) {
		final User user = UUIDCookieLoader.userFromRequest(request);
		if (user == null) {
			return new Response(403);
		}

		if (!request.protocolScheme().equalsIgnoreCase("https"))
			return new Response(400);

		if (request.getType() == RequestType.GET) {
			// TODO: Generate payload and provide SHA256 of cert
			final String prompt = StringsUtil.randomStringAlphabet(6);
			final byte[] cert = request.socket_tlsHash();
			final byte[] hash = Hashes.get(Hashables.SHA256).raw_hash(ByteUtil.combine(cert, user.uuid().getBytes(), prompt.getBytes()));
			final String hashed = ByteUtil.getHex(hash);
			user.setExpectedResults(new String[]
				{ hashed });
			final UniJsonValue result = UniJsonValue.object(2);
			result.add("cert", ByteUtil.getHex(cert));
			result.add("prompt", "null");
			return new Response(200, result, result);
		} else {
			// TODO: Validate response
		}
		return null;
	}

}
